package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.qo.PageQo;
import cn.wolfcode.rbac.qo.QueryObject;
import cn.wolfcode.rbac.service.IRoleService;
import cn.wolfcode.rbac.web.annotation.RequiredPermission;
import cn.wolfcode.rbac.utils.R;
import cn.wolfcode.rbac.web.vo.RolePermissionVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(allowCredentials = "true")
@RequestMapping("/api/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @RequiredPermission(name = "角色分页列表",expression = "role:list")
    @GetMapping("list")
    public R list(QueryObject qo){
        PageInfo<Role> pageInfo = roleService.list(qo);
        PageQo pageQo = new PageQo(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getList(), pageInfo.getTotal());
        return R.ok(pageQo);
    }

    @RequiredPermission(name = "角色删除",expression = "role:delete")
    @DeleteMapping("delete/{id}")
    public R delete(@PathVariable Long id){
        roleService.deleteRoleById(id);
        return R.ok("角色删除成功");
    }

    /**
     * 根据角色id查询角色信息
     * @param id
     * @return
     */
    @RequiredPermission(name = "角色信息",expression = "role:info")
    @GetMapping("info/{id}")
    public R info(@PathVariable Long id){
        Role role = roleService.get(id);
        return R.ok(role);
    }

    /**
     * 根据员工id查询角色信息
     * @param id
     * @return
     */
    @RequiredPermission(name = "员工的角色信息",expression = "role:query")
    @GetMapping("query/{id}")
    public R query(@PathVariable Long id){
        List<Role> roleIds = roleService.query(id);
        return R.ok(roleIds);
    }

    @RequiredPermission(name = "保存或更新角色信息",expression = "role:saveOrUpdate")
    @PostMapping("saveOrUpdate")
    public R saveOrUpdate(@RequestBody RolePermissionVo rolePermissionVo){
        if(rolePermissionVo.getRole().getId() == null){
            roleService.save(rolePermissionVo);
            return R.ok("角色信息保存成功");
        }else{
            roleService.update(rolePermissionVo);
            return R.ok("角色信息更新成功");
        }
    }
}
